'use strict';

var exec = require('child_process').execSync;
var _ = require('lodash');
var fs = require('fs');

/**
 * find pid of tcp port use cmd "netstat -ntpl|grep ....."
 * 
 * @param  {Number} port tcp port
 * @return {Number|0} 
 */
function findPid(port){
  try{
    var lines = exec(`2>/dev/null netstat -ntlp|grep java|grep LISTEN|grep ${port}`)
      .toString().trim().split('\n');

    if(lines.length>=1){
      var pid = lines[0].replace(/\s+/g,',').split(',')[6].split('/')[0];
      return pid?parseInt(pid):0;
    }else{
      return 0;
    }  
  }catch(error){
    return 0;
  }
}

/**
 * jstat -gc pid|sed '1d'|sed 's#\s\+#,#g'|awk -F ',' '{print $1 $2'
 * @param  {[type]} pid [description]
 * @return {[type]}     [description]
 */
function jstat(pid){
  
  if(pid<=0){
    return {
      error: 'no such pid', 
    };
  }

  var cmdlines = fs.readFileSync(`/proc/${pid}/cmdline`).toString().trim();

  var java = cmdlines.substring(0, cmdlines.indexOf('\u0000'));

  var jstat = java.replace('bin/java', 'bin/jstat');

  var javaVer = '';
  var vendor = '';
  try{
    var _v = exec(`${java} -version 2>&1|head -n1|grep -o '1\.[0-9]'`).toString().trim();
    javaVer = parseInt(_v.replace('.')) - 10;

    var vs = exec(`${java} -version 2>&1|sed '1,2d'`).toString().trim().toLowerCase();
    if(vs.indexOf('hotspot')>=0){
      vendor = 'hotspot';
    }else if(vs.indexOf('jrockit')>=0){
      vendor = 'jrockit';
    }else{
      vendor = 'unknown';
    }


    if(pid>0){
      var r = {};
      var lines = exec(`2>/dev/null ${jstat} -gc ${pid}`).toString().trim().split('\n');
      var headers = lines[0].trim().replace(/\s+/g,',').split(',');
      var values = lines[1].trim().replace(/\s+/g,',').split(',');
      _.forEach(headers, function(e, idx){
        r[e] = values[idx];
      });

      return {
        java: {
          version: javaVer,
          vendor: vendor
        },
        data: r
      };
    }else{
      return {
        java: {
          version: javaVer,
          vendor: vendor
        },
        error: 'no such pid', 
      };
    }
  }catch(error){
    return {
      java: {
        version: javaVer,
        vendor: vendor
      },
      error: error.toString()
    };
  }


}

exports.jstat = function (port){
  return jstat(findPid(port));
};

